<?php

/**
 * buses actions.
 *
 * @package    SistemaRutasEc
 * @subpackage buses
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class inicioActions extends sfActions {

    function cross_app_url_for($appname, $url, $absolute = false, $env = null, $debug = false) {

        $initial_app = sfContext::getInstance()->getConfiguration()->getApplication();
        $initial_web_controler = basename(sfContext::getInstance()->getRequest()->getScriptName());
        $initial_config = sfConfig::getAll();
        // get the environment
        if (is_null($env)) {
            $env = sfContext::getInstance()->getConfiguration()->getEnvironment();
        }

        // context creation
        if (!sfContext::hasInstance($appname)) {
            $context = sfContext::createInstance(ProjectConfiguration::getApplicationConfiguration($appname, $env, $debug), $appname);
        } else {
            $context = sfContext::getInstance($appname);
        }
        $web_url = $context->getController()->genUrl($url, $absolute);
        sfContext::switchTo($initial_app);
        sfConfig::add($initial_config);
        unset($context);

        //remove initial web controler
        // genUrl use $this->context->getRequest()->getScriptName();, its a call to $_SERVER
        // so starting the shameless part !
        $script_name = $appname;
        if (($env != 'prod') and $env) {
            $script_name.='_' . $env;
        } elseif ($script_name == "frontend") {
            $script_name = "index";
        }
        $script_name.='.php';
        // check if this file exist
        if (!file_exists(sfConfig::get('sf_web_dir') . DIRECTORY_SEPARATOR . $script_name))
            throw new sfException('can t find ' . $script_name . ' in the web directory');
        $web_url = str_replace($initial_web_controler, $script_name, $web_url);

        return $web_url;
    }

    public function executeIndex($sfWebRequest) {



        if (sfContext::getInstance()->getUser()->isAuthenticated()) {
            
            if ($this->getUser()->hasPermission("union") == true) {
                $this->s = "Union Cariamanga";
                $this->setTemplate('home');
            } else if ($this->getUser()->hasPermission("loja") == true) {
                $this->s = "Loja Internacional";
                $this->setTemplate('home');
            } else {
                //$this->useHelper('crossAppLink');
                //sfContext::getInstance()->getConfiguration()->loadHelpers( 'crossAppLink' );
                $this->redirect($this->cross_app_url_for('backend', 'inicioadmin/index'));
                //$this->getUser()->setFlash('notice', 'Necesita tener las credenciales de Acceso al Sistema');
                //$this->redirect('http://localhost/SistemaRutasEc/web/backend_dev.php');
                //$this->redirect('backend','inicioadmin/index');
            }
        }
    }

    public function executeBusqueda(sfWebRequest $request) {
        $this->salida = $request->getParameter('salida');
        $this->llegada = $request->getParameter('llegada');

        $this->reglas = Doctrine_Core::getTable('regla')
                ->createQuery('r')
                ->leftJoin('r.Cooperativa c')
                ->execute();
    }

    public function executeIndex2($sfWebRequest) {
        
    }

    public function executeVender2($sfWebRequest) {
        
    }

    public function executeCanjear(sfWebRequest $request) {
        
    }

    public function executeConfirmar(sfWebRequest $request) {
        if ($request->isMethod('POST')) {
            try {
                $nombre = '';
                if ($this->getUser()->getGuardUser()->hasPermission('union')) {
                    $nombre = 'Union Cariamanga'; //FIXME
                } else if ($this->getUser()->getGuardUser()->hasPermission('loja')) {
                    $nombre = 'Loja Internacional'; //FIXME
                }

                $id = $request->getParameter('boleto');
                $this->boleto = Doctrine_Core::getTable('Boleto')->createQuery('b')
                        ->leftJoin('b.Turno t')
                        ->leftJoin('t.Cooperativa c')
                        ->where('b.id_bo = ?', $id)
                        ->andWhere('c.nombre = ?', $nombre)
                        ->andWhere('b.estado = ?', Boleto::RESERVADO)
                        ->fetchOne();

                if (false == $this->boleto)
                    $this->getUser()->setFlash('error', 'El boleto no existe o ya ha sido confirmado');
            } catch (Exception $error) {
                $this->dispatcher->notify(new sfEvent($this, 'application.log', array('priority' => sfLogger::ERR, $error->getMessage())));
            }
        }
    }

    public function executeVender(sfWebRequest $request) {
        try {
            $nombre = '';
            if ($this->getUser()->getGuardUser()->hasPermission('union')) {
                $nombre = 'Union Cariamanga'; //FIXME
            } else if ($this->getUser()->getGuardUser()->hasPermission('loja')) {
                $nombre = 'Loja Internacional'; //FIXME
            }

            $id = $request->getParameter('boleto');
            $this->boleto = Doctrine_Core::getTable('Boleto')->createQuery('b')
                    ->leftJoin('b.Turno t')
                    ->leftJoin('t.Cooperativa c')
                    ->where('b.id_bo = ?', $id)
                    ->andWhere('c.nombre = ?', $nombre)
                    ->andWhere('b.estado = ?', Boleto::RESERVADO)
                    ->fetchOne();

            //validar fecha y hora
            $fechaTurno = strtotime($this->boleto->getTurno()->fecha . ' ' . $this->boleto->getTurno()->hora);
            $fechaActual = strtotime(sprintf('+%d hours', Boleto::TIEMPO_LIMITE));

            if ($fechaTurno >= $fechaActual) {
                $this->boleto->estado = Boleto::VENDIDO;
                $this->boleto->save();
                $this->getUser()->setFlash('notice', 'La reservación ha sido confirmada exitosamente.');
            } else {
                $this->getUser()->setFlash('error', 'No se pudo confirmar la reservación, ha transcurrido el tiempo limite');
            }
        } catch (Exception $error) {
            $this->dispatcher->notify(new sfEvent($this, 'application.log', array('priority' => sfLogger::ERR, $error->getMessage())));
            $this->getUser()->setFlash('error', 'Ha ocurrido un error al confirmar la reservación.');
        }

        return $this->redirect('inicio/index');
    }

    public function executeCancelar(sfWebRequest $request) {
        try {
            $nombre = '';
            if ($this->getUser()->getGuardUser()->hasPermission('union')) {
                $nombre = 'Union Cariamanga'; //FIXME
            } else if ($this->getUser()->getGuardUser()->hasPermission('loja')) {
                $nombre = 'Loja Internacional'; //FIXME
            }

            $id = $request->getParameter('boleto');
            $this->boleto = Doctrine_Core::getTable('Boleto')->createQuery('b')
                    ->leftJoin('b.Turno t')
                    ->leftJoin('t.Cooperativa c')
                    ->where('b.id_bo = ?', $id)
                    ->andWhere('c.nombre = ?', $nombre)
                    ->andWhere('b.estado = ?', Boleto::RESERVADO)
                    ->fetchOne();

            $this->forward404Unless($this->boleto);

            $this->boleto->estado = Boleto::CANCELADO_RESERVACION;
            $this->boleto->save();
            $this->getUser()->setFlash('notice', 'La reservación ha sido cancelada exitosamente.');
        } catch (Exception $error) {
            $this->dispatcher->notify(new sfEvent($this, 'application.log', array('priority' => sfLogger::ERR, $error->getMessage())));
            $this->getUser()->setFlash('error', 'Ha ocurrido un error al cancelar la reservación.');
        }

        return $this->redirect('inicio/index');
    }

    public function executeCanjear2($sfWebRequest) {
        
    }

    public function executeAnular($sfWebRequest) {
        
    }

    public function executeAnular2($sfWebRequest) {
        
    }

    public function executeReservacionesUsuario($sfWebRequest) {
        
    }

    public function executeReservaciones($sfWebRequest) {
        
    }

    public function executeReservaciones2($sfWebRequest) {
        
    }

    public function executeListaReservacion($sfWebRequest) {
        
    }

    public function executeListaReservacion2($sfWebRequest) {
        
    }

}
